package com.tledu.production.core.aspect;

import com.tledu.production.core.exception.CustomException;
import com.tledu.production.core.result.AjaxResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 对所有controller增强
 *
 * @author Antg
 * @date 2021/8/13  20:25
 */
@ControllerAdvice
public class ExceptionControllerAspect {
    // 在ControllerAdvice里写的异常处理，会在全局生效
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Object exceptionHandle(CustomException e, HttpServletRequest req) {
        // 普通页面报错调到错误页面，ajax请求报错，返回json
        // 判断这个请求是普通请求还是ajax请求
        if ("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
            // 这是ajax请求
            return new AjaxResult<Void>(e.getMessage(), e.getCode());
        } else {
            // 这个就普通页面，加了ResponseBody怎么返回页面
            ModelAndView mv = new ModelAndView("error/error");
            mv.getModel().put("msg", e.getMessage());
            return mv;
        }
    }
}
